package com.iqik.redis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping("/set/{key}/{value}/{time}")
    public String setValue(@PathVariable(name = "key") String key,
                           @PathVariable(name = "value") String value,
                           @PathVariable(name = "time") long time) {
        redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
        return "success";
    }

    @RequestMapping("/get/{key}")
    public String getValue(@PathVariable(name = "key") String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }

    @RequestMapping("/get/{keys}")
    public String getValues(@PathVariable(name = "keys") String key) {
        String[] keys = key.split(",");
        StringBuilder builder = new StringBuilder();
        for (String k: keys){
            builder.append(String.format("%s=%s", k, (String) redisTemplate.opsForValue().get(key)));
        }
        return builder.toString();
    }
}
